package com.yfqy.app.modules.wechat.util;

import com.yfqy.app.modules.wechat.model.WechatRefundResponse;
import com.yfqy.app.util.MD5Util;
import lombok.extern.slf4j.Slf4j;

import java.util.Map;
import java.util.TreeMap;
import java.util.UUID;

@Slf4j
public class WechatPayUtil {

    /**
     * 生成随机字符串
     */
    public static String generateNonceStr() {
        return UUID.randomUUID().toString().replace("-", "").substring(0, 32);
    }

    /**
     * 生成时间戳
     */
    public static String generateTimestamp() {
        return String.valueOf(System.currentTimeMillis() / 1000);
    }

    /**
     * 生成MD5签名
     */
    public static String generateSign(Map<String, String> params, String key) {
        // 1. 参数名ASCII码从小到大排序
        TreeMap<String, String> sortedParams = new TreeMap<>(params);

        // 2. 拼接字符串
        StringBuilder sb = new StringBuilder();
        for (Map.Entry<String, String> entry : sortedParams.entrySet()) {
            if (entry.getValue() != null && !entry.getValue().isEmpty()) {
                sb.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
            }
        }
        sb.append("key=").append(key);

        // 3. MD5加密并转大写
        try {
            /*MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] digest = md.digest(sb.toString().getBytes("UTF-8"));
            StringBuilder result = new StringBuilder();
            for (byte b : digest) {
                result.append(String.format("%02x", b));
            }*/
            return MD5Util.encrypt(sb.toString()).toUpperCase();
        } catch (Exception e) {
            log.error("生成签名失败", e);
            return null;
        }
    }

    /**
     * 验证签名
     */
    public static boolean verifySign(Map<String, String> params, String key, String sign) {
        String calculatedSign = generateSign(params, key);
        return sign != null && sign.equals(calculatedSign);
    }

    /**
     * 将Map转换为XML字符串
     */
//    public static String mapToXml(Map<String, String> params) {
//        try {
//            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
//            DocumentBuilder builder = factory.newDocumentBuilder();
//            Document document = builder.newDocument();
//
//            Element root = document.createElement("xml");
//            document.appendChild(root);
//
//            for (Map.Entry<String, String> entry : params.entrySet()) {
//                Element element = document.createElement(entry.getKey());
//                if (entry.getValue() != null) {
//                    element.appendChild(document.createTextNode(entry.getValue()));
//                }
//                root.appendChild(element);
//            }
//
//            TransformerFactory transformerFactory = TransformerFactory.newInstance();
//            Transformer transformer = transformerFactory.newTransformer();
//            transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
//            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
//
//            StringWriter writer = new StringWriter();
//            transformer.transform(new DOMSource(document), new StreamResult(writer));
//
//            return writer.toString();
//        } catch (Exception e) {
//            log.error("Map转XML失败", e);
//            return null;
//        }
//    }
//
//    /**
//     * 将XML字符串转换为Map
//     */
//    public static Map<String, String> xmlToMap(String xml) {
//        Map<String, String> result = new HashMap<>();
//        try {
//            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
//            DocumentBuilder builder = factory.newDocumentBuilder();
//            Document document = builder.parse(new ByteArrayInputStream(xml.getBytes(StandardCharsets.UTF_8)));
//
//            Element root = document.getDocumentElement();
//            NodeList nodeList = root.getChildNodes();
//
//            for (int i = 0; i < nodeList.getLength(); i++) {
//                if (nodeList.item(i).getNodeType() == org.w3c.dom.Node.ELEMENT_NODE) {
//                    Element element = (Element) nodeList.item(i);
//                    String tagName = element.getTagName();
//                    String textContent = element.getTextContent();
//                    result.put(tagName, textContent);
//                }
//            }
//        } catch (Exception e) {
//            log.error("XML转Map失败", e);
//        }
//        return result;
//    }

    /**
     * 获取客户端IP地址
     */
    public static String getClientIp() {
        return "127.0.0.1"; // 简化处理，实际项目中需要从请求中获取
    }



    /**
     * 检查微信退款是否成功
     */
    public static boolean isRefundSuccess(WechatRefundResponse response) {
        return response != null &&
                "SUCCESS".equals(response.getReturnCode()) &&
                "SUCCESS".equals(response.getResultCode());
    }
}
